LINQ
(LINQ stands for language-integrated query)
Is the single most important new feature in C# 3.0. It adds an entirely new syntactic element, several new keywords, and a powerful new capability. The inclusion of LINQ has significantly increased the scope of the language, expanding the range of tasks to which C# can be applied. LINQ adds to C# the ability to generate queries for any LINQ-compatible data source. The query capability is fully integrated into the C# language. In addition to using LINQ with SQL, LINQ can be used with XML files and ADO.NET datasets. Perhaps equally important, it can also be used with C# arrays and collections.
LINQ provides a uniform way to retrieve data from any object that implements the IEnumerable<T> interface. With LINQ, arrays, collections, relational data, and XML are all potential data sources.
LINQ is supported by a set of interrelated features, including the query syntax added to the C# language, lambda expressions, anonymous types, and extension methods. After a query has been created, it can be executed. One way this is done is by using the query in a foreach loop.
In order for a source of data to be used by LINQ, it must implement the IEnumerable interface. There are two forms of this interface: one generic, one not. In general, it is easier if the data source implements the generic version, IEnumerable<T>, where T specifies the type of data being enumerated. All C# arrays support IEnumerable<T>. Thus, we can use arrays to demonstrate the central concepts of LINQ. Understand, however, that LINQ is not limited to arrays.
The General Form of a Query
Program on LINQ in Arrays
using System;
using System.Linq;
class sample
{
static void Main()
{
int[] sal = { 2100, 3200, 1245, 3455, 5466, 2300, 6500 };
var k = from n in sal where n > 3000
select n;
Console.WriteLine("SAlaries:");
foreach (int i in k)
Console.WriteLine(i);
Console.WriteLine("\nLessthan 3000 salary");
k=from p in sal where p<3000 select p;
foreach (int j in k)
Console.WriteLine (j);
Console.WriteLine("\n Salary >3000 and <4000");
k=from q in sal where q>3000 where q<4000 select q;
foreach (int m in k)
Console.WriteLine(m);
}
}
Program on Strings using LINQ
using System;
using System.Linq;
class sample
{
static void Main(string[] args)
{
string[] na = { "PRASAD", "murali", "venu", "PAVAN", "Sony" };
var s = from k in na where k.Equals("PRASAD") || k.Equals("Sony") select k;
foreach (string p in s)
Console.WriteLine(p);
Console.WriteLine(" Print the Names who are in Capitals");
s = from k in na where k.Contains (k.ToUpper ()) select k;
foreach (string p in s)
Console.WriteLine(p);
}
}
Program on Orderby clause
using System;
using System.Linq;
class sample
{
static void Main()
{
int[] sal = { 8,3,9,2,1,4,6 };
var k = from n in sal
orderby n
select n;
Console.WriteLine("Sorted Values are");
foreach (int i in k)
Console.WriteLine(i);
}
}
Select
select clause determines what types of elements are obtained by a query. select is not limited to this simple action. It can return a specific portion of the range variable.
Syntax: Select expression
Program on Select expression
using System;
using System.Linq;
class sample
{
static void Main()
{
int[] sal = { 8,3,9,2,1,4,6 };
var k = from n in sal
orderby n
select Math.Pow(n, 2);
Console.WriteLine("Values are pwoer by 2");
foreach (int i in k)
Console.WriteLine(i);
}
}
Program on LINQ in Objects
using System;
using System.Linq;
class Address
{
public string Name ;
public string City;
public Address(string n, string a)
{
Name = n;
City = a;
}
}
class sample
{
static void Main()
{
Address[] addrs = {
new Address("Prasad","Vuyyuru"),
new Address("Murali", "Hyderabad"),
new Address("Saroja", "Banglore"),
};
var e = from entry in addrs
select entry.City ;
Console.WriteLine("The Cities are");
foreach (string s in e) Console.WriteLine(" " + s);
}
}
Group
One of the most powerful query features is provided by the group clause because it enables you to create results that are grouped by keys.
Syntex: group range-variable by key
The result of group is a sequence that contains elements of type IGrouping<TKey,
TElement>, which is declared in the System.Linq namespace.
Program on Group clause
using System;
using System.Linq;
class vision
{
static void Main()
{
string[] websites = { "yahoo.com", "vision.net", "prasad.net",
"cerner.com", "nu.org", "vuyyuru.org",
"etv.tv", "bbc.net", "sun.tv" };
var webAddrs = from addr in websites
where addr.LastIndexOf(".") != -1
group addr by addr.Substring(addr.LastIndexOf("."));
foreach (var sites in webAddrs)
{
Console.WriteLine("Websites grouped by " + sites.Key);
foreach (var site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
// using IGrouping
foreach (IGrouping<string, string> sites in webAddrs)
{
Console.WriteLine("Websites grouped by " + sites.Key);
foreach (string site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
}
}
Program on into with group clause
using System;
using System.Linq;
class vision
{
static void Main()
{
string[] websites = { "yahoo.com", "vision.net", "prasad.net",
"cerner.com", "nu.org", "vuyyuru.org",
"etv.tv", "bbc.net", "sun.tv" };
var webAddrs = from addr in websites
where addr.LastIndexOf(".") != -1
group addr by addr.Substring(addr.LastIndexOf("."))
into ws
where ws.Count() > 2
select ws;
foreach (var sites in webAddrs)
{
Console.WriteLine("Websites grouped by " + sites.Key);
foreach (var site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
}
}
let
In a query, you will sometimes want to temporarily retain a value. For example, you might want to create an enumerable variable that can, itself, be queried. Or, you might want to store a value that will be used later on in a where clause. Whatever the purpose, these types of actions can be accomplished through the use of let.
Syntax: let name = expression
Program on LET
using System;
using System.Linq;
class sample
{
static void Main()
{
string[] strs = { "prasad", "vision", "murali" };
var chrs = from str in strs
let chrArray = str.ToCharArray()
from ch in chrArray
orderby ch
select ch;
Console.WriteLine("The individual characters in sorted order:");
foreach (char c in chrs) Console.Write(c + " ");
}
}
Query Methods
The query methods are defined by System.Linq.Enumerable and are implemented as
extension methods that extend the functionality of IEnumerable<T>. (Query methods are also defined by System.Linq.Queryable, which extends the functionality of IQueryable<T>.
Program on Select and Where method
using System;
using System.Linq;
class sample
{
static void Main()
{
int[] nums = { 1, -2, 3, 0, -4, 5 };
var posNums = nums.Where(n => n > 0).Select(r => r);
Console.WriteLine("The positive values in nums:");
foreach (int i in posNums) Console.WriteLine(i);
}
}
Program on GroupBy clause
using System;
using System.Linq;
class sample
{
static void Main()
{
string[] websites = { "yahoo.com", "vision.net", "prasad.net",
"cerner.com", "nu.org", "vuyyuru.org",
"etv.tv", "bbc.net", "sun.tv" };
var webAddrs = websites.Where(w => w.LastIndexOf(".") != 1).
GroupBy(x => x.Substring(x.LastIndexOf(".", x.Length)));
foreach (var sites in webAddrs)
{
Console.WriteLine("Websites grouped by " + sites.Key);
foreach (var site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
}
}
Program on All Methods
using System;
using System.Linq;
class sample {
static void Main() {
int[] nums = { 3, 1, 2, 5, 4 };
Console.WriteLine("The minimum value is " + nums.Min());
Console.WriteLine("The maximum value is " + nums.Max());
Console.WriteLine("The first value is " + nums.First());
Console.WriteLine("The last value is " + nums.Last());
Console.WriteLine("The sum is " + nums.Sum());
Console.WriteLine("The average is " + nums.Average());
if(nums.All(n => n > 0))
Console.WriteLine("All values are greater than zero.");
if(nums.Any(n => (n % 2) == 0))
Console.WriteLine("At least one value is even.");
if(nums.Contains(3))
Console.WriteLine("The array contains 3.");
}
}